package router

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

type XmlObject struct{
	Profession string `xml:"profession"`
	Salary int `xml:"salary"`
}

type QueryData struct{
	Name string `form:"name" json:"name" xml:"name"`
	Age int `form:"age" json:"age" xml:"age"` 
	Prices []int `form:"prices" json:"prices" xml:"prices"`
	Users XmlObject `xml:"users"`
}

func ShouldBindKnowledge(r *gin.Engine){
	//测试shouldBindQuery
	r.POST("/shouldBind",func(ctx *gin.Context) {
		res := QueryData{}
		//使用结构体实例指针，这样才能影响到结构体实例本身
		err := ctx.ShouldBind(&res)
		if err!=nil{
			//一定要打印错误日志
			fmt.Printf("解析出错！！,原因为%v\n",err.Error())
			ctx.JSON(500,gin.H{
				"msg":err.Error(),
			})
		}else{
			fmt.Printf("接收到的参数为%#v\n",res)
			ctx.JSON(200,map[string]interface{}{
				"msg":"操作成功",
				"data":res,
			})
		}
	})


	//测试shouldBindQuery
	r.GET("/shouldBindQuery",func(ctx *gin.Context) {
		res := QueryData{}
		err := ctx.ShouldBindQuery(&res)
		if err!=nil{
			//一定要打印错误日志
			fmt.Printf("解析出错！！,原因为%v\n",err.Error())
		}else{
			fmt.Printf("接收到的参数为%#v\n",res)
		}
	})

	//测试shouldBindJSON
	r.POST("/shouldBindJSON",func(ctx *gin.Context) {
		res := QueryData{}
		err :=ctx.ShouldBindJSON(&res)
		if err!=nil{
			fmt.Printf("解析出错！！,原因为%v\n",err.Error())
		}else{
			fmt.Printf("接收到的参数为%#v\n",res)
		}
	})

	//测试shouldBindXml
	r.POST("/shouldBindXml",func(ctx *gin.Context) {
		res := QueryData{}
		if err:=ctx.ShouldBindXML(&res);err!=nil{
			fmt.Printf("解析出错！！，原因为%v\n",err.Error())
		}else{
			fmt.Printf("接收到的参数为%#v\n",res)
		}
	})
}